<!-- wangeditor富文本编辑器 -->
<template>
  <div>
    <el-form
      label-position="top"
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleFormRef"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model.trim="ruleForm.title" autofocus></el-input>
      </el-form-item>

      <div style="border: 1px solid #ccc">
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="toolbarConfig"
          :mode="mode"
        />
        <Editor
          style="height: 280px; overflow-y: hidden"
          v-model="valueHtml"
          :defaultConfig="editorConfig"
          :mode="mode"
          @onCreated="handleCreated"
        />
      </div>
    </el-form>
  </div>
</template>
<script>
import request from "utils/request";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  watch,
  reactive,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";

export default {
  name: "MyWangeditor",
  components: { Editor, Toolbar },
  setup(props, { emit }) {
    const route = useRoute();

    const { id } = route.query;

    const ruleFormRef = ref();
    const ruleForm = reactive({
      title: "",
    });

    const rules = reactive({
      title: [{ required: true, trigger: "blur" }],
    });

    const submitForm = () => {
      ruleFormRef.value.validate(async (valid) => {
        if (valid) {
          let ret = await request.post("/modifyNote", {
            id: id,
            title: ruleForm.title,
            content: valueHtml.value,
          });
          if (ret.code == 200) {
            ElMessage({
              type: "success",
              message: "添加成功",
              showClose: true,
              duration: 1000,
            });
          } else {
            ElMessage({
              type: "error",
              message: "添加失败",
              showClose: true,
              duration: 1000,
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    // 内容 HTML
    const valueHtml = ref("<p><br></p>");
    console.log(valueHtml, "valueHtmlvalueHtmlvalueHtmlvalueHtml");
    emit("valueHtml", valueHtml);
    // 模拟 ajax 异步获取内容
    onMounted(async () => {
      if (id) {
        let ret = await request.post("/findNote", { id });
        if (ret.code == 200) {
          ruleForm.title = ret.data.title;
          valueHtml.value = ret.data.content;
        }
      }
    });

    function init(data) {
      console.log("data", data);
      valueHtml.value = data;
    }
    watch(valueHtml, (val) => {
      console.log(val, "val");
      emit("BoxValue", val);
    });
    const toolbarConfig = {
      //删除工具栏中不需要的选项比如视频就是group-video
      excludeKeys: [
        "headerSelect",
        "italic",
        "group-more-style", // 排除菜单组，写菜单组 key 的值即可
        "group-video",
      ],
    };

    const uploadImg = async (file, insertFn) => {
      const imgData = new FormData(); // 创建form对象
      imgData.append("file", file); // 通过append向form对象添加数据
      imgData.append("origin",'note')
      const config = {
        headers: { "Content-Type": "multipart/form-data" },
      };
      let ret = await request.upload("/upload", imgData, config);
      if (ret.code == 200) {
        insertFn(ret.data);
      }
    };

    const editorConfig = {
      placeholder: "请输入内容...",
      // 所有的菜单配置，都要在 MENU_CONF 属性下
      MENU_CONF: {
        //配置上传图片
        uploadImage: {
          customUpload: uploadImg,
        },
      },
    };

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });

    const handleCreated = (editor) => {
      editorRef.value = editor; // 记录 editor 实例，重要！
    };

    return {
      editorRef,
      valueHtml,
      mode: "default", // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated,
      init,
      ruleFormRef,
      ruleForm,
      rules,
      submitForm,
    };
  },
};
</script>
